﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace YABE.Models
{
    public class Routing
    {
       
         public static RouteCollection Routes 
        { 
            get { return RouteTable.Routes; } 
        }

  
        /// <summary> 
        /// Gets the configured routes. 
        /// </summary> 
        /// <returns></returns> 
         public static List<MVCRoute> GetConfiguredRoutes() 
        {
            using (YabeDataContext context = YabeDataManager.Instance.DataContext)
            {
                return (from b in context.MVCRoutes
                    where b.routeIsActive == true
                    orderby b.routeOrder
                    select b).ToList();
            }
            
        } 
  
        /// <summary> 
        /// Clears current and readds application routes. 
        /// </summary> 
        public static void ResetAppRoutes() 
        { 
            Routes.Clear(); 
            SetAppRoutes(); 
        } 
  
        /// <summary> 
        /// Sets the application routes. 
        /// </summary> 
        public static void SetAppRoutes() 
        {
            List<MVCRoute> configuredRoutes = GetConfiguredRoutes(); 
            SetAppRoutes(configuredRoutes); 
        } 
  
        /// <summary> 
        /// Sets the application routes. 
        /// </summary> 
        /// <param name="configuredRoutes">Collection of routes to add to the application's routing table.</param> 
        public static void SetAppRoutes(List<MVCRoute> configuredRoutes) 
        { 
            //add the routes to the RouteCollection 
            foreach (MVCRoute route in configuredRoutes) 
            { 
                //create RouteValueDictionary objects to add the default values and contraints to the route 
                RouteValueDictionary constraints = new RouteValueDictionary(); 
                RouteValueDictionary routeVals = new RouteValueDictionary();

                foreach (MVCRouteParam param in route.MVCRouteParams ) 
                { 
                    routeVals.Add(param.paramKey, param.paramValue); 
                    if (!string.IsNullOrEmpty(param.paramConstraint)) 
                    { 
                        constraints.Add(param.paramKey, param.paramConstraint); 
                    } 
                } 
  
                //create the route using the defaults set above 
                RouteTable.Routes.Add(new Route(route.routePattern, new MvcRouteHandler()) 
                { 
                    Defaults = routeVals, 
                    Constraints = constraints 
                }); 
            } 
        } 
    } 
}
